package com.lindroy.jetpacknotes.utils

import android.os.Handler
import android.os.Looper
import androidx.annotation.MainThread
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

/**
 * @author Lin
 * @date 2023/12/17
 * @function
 */
class FragmentViewBindingProperty<in T : Fragment, out VB : ViewBinding>(
    private val viewBindingFactory: (T) -> VB
) : ReadOnlyProperty<T, VB> {

    private var viewBinding: VB? = null

    override fun getValue(thisRef: T, property: KProperty<*>): VB {
        viewBinding?.let { return it }

        val lifecycle = thisRef.viewLifecycleOwner.lifecycle
        val viewBinding = viewBindingFactory(thisRef)
        if (lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) {
            lifecycle.addObserver(OnDestroyLifecycleObserver())
            this.viewBinding = viewBinding
        }
        return viewBinding
    }

    private inner class OnDestroyLifecycleObserver : DefaultLifecycleObserver {
        private val mainHandler = Handler(Looper.getMainLooper())

        @MainThread
        override fun onDestroy(owner: LifecycleOwner) {
            super.onDestroy(owner)
            mainHandler.post { viewBinding = null }
        }
    }

}